<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <el-row :gutter="15">
        <el-col :span="2.5" class="text_lh">选择商品分类:</el-col>
        <el-col :span="10">
          <!-- 级联选择器 -->
          <el-cascader
            :props="cascaderCate"
            clearable
            v-model="selc_cateID"
            :options="CateList"
            expand-trigger="hover"
            @change="CateChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏选项卡 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="first"></el-tab-pane>
        <el-tab-pane label="静态属性" name="second"></el-tab-pane>
        <el-button
          type="primary"
          size="mini"
          v-if="activeName == 'first'"
          @click="openAdd($event)"
        >添加参数</el-button>
        <el-button type="primary" size="mini" v-else @click="openAdd($event)">添加属性</el-button>
        <!-- 渲染数据的表格 -->
        <el-table :data="tableData" stripe border style="width: 100%">
          <el-table-column type="expand" width="50">
            <!-- 展开行模板 -->
            <template slot-scope="scope">
              <el-tag
                :key="tag"
                v-for="tag in scope.row.attr_vals"
                closable
                :disable-transitions="false"
                @close="delTag(scope.row,tag)"
              >{{tag}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="AddTag(scope.row)"
                @blur="AddTag(scope.row)"
              ></el-input>
              <el-button v-else id="btns" size="small" @click="showInput">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#" width="50"></el-table-column>
          <el-table-column prop="attr_name" :label="activeName==='first'?'参数名称':'属性名称'"></el-table-column>
          <el-table-column prop="name" label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="openEdit(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteAttr(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tabs>
    </el-card>
    <!-- 添加属性对话框 -->
    <el-dialog
      :title="addDialogInfo=='添加参数'?'添加动态参数':'添加静态属性'"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="closeAdd"
    >
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="100px">
        <el-form-item :label="addDialogInfo=='添加参数'?'参数名称':'属性名称'" prop="attr_name">
          <el-input v-model="dialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAdd">取 消</el-button>
        <el-button type="primary" @click="AddTrue">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改属性对话框 -->
    <el-dialog
      :title="activeName=='first'?'修改动态参数':'修改静态属性'"
      :visible.sync="EditdialogVisible"
      width="50%"
      :before-close="closeAdd"
    >
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="100px">
        <el-form-item :label="activeName=='first'?'参数名称':'属性名称'" prop="attr_name">
          <el-input v-model="dialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAdd">取 消</el-button>
        <el-button type="primary" @click="EditTrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      EditdialogVisible: false,
      dialogVisible: false,
      activeName: 'first',
      tableData: [],
      cascaderCate: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      CateList: [],
      selc_cateID: [],
      params: {
        sel: 'only'
      },
      inputVisible: false,
      inputValue: '',
      // 对话框内双向绑定的对象
      dialogForm: {
        attr_name: ''
      },
      // 验证规则
      rules: {
        attr_name: [
          { required: true, message: '请输入参数或属性名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 添加属性时的信息
      addDialogInfo: '',
      // 编辑时用来验证和原名称是否相同
      YZ: {
        attr_name: '',
        id: 0,
        sel: '',
        attr_vals:''
      }
    }
  },
  methods: {
    //   tab栏按钮的点击事件
    handleClick(str) {
      if (this.selc_cateID.length < 3) return
      this.activeName = str.name
      this.getAttrList()
    },
    // 获取分类数据的函数
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取分类列表失败~')
      this.CateList = res.data
    },
    // 获取属性或参数列表的函数
    async getAttrList() {
      if (this.activeName === 'first') {
        this.params.sel = 'many'
      }
      const { data: result } = await this.$http.get(
        '/categories/' +
          this.selc_cateID[this.selc_cateID.length - 1] +
          '/attributes',
        { params: this.params }
      )
      if (result.meta.status !== 200)
        return this.$message.error('获取参数,属性失败~')
      result.data.forEach((item, i) => {
        if (item.attr_vals) {
          item.attr_vals = item.attr_vals.split(' ')
        }
      })
      this.tableData = result.data
      this.params.sel = 'only'
    },
    // 级联选择器改变触发函数
    CateChange(res) {
      if (res.length < 3) {
        this.selc_cateID = []
        this.tableData = []
        return
      }
      this.selc_cateID = res
      this.getAttrList()
    },
    // tag便签上面的关闭按钮的处理事件
    delTag(row, tag) {
      // 点后后先把row数组中的要删除的那一项移出
      row.attr_vals.forEach((item, i) => {
        if (item === tag) {
          row.attr_vals.splice(i, 1)
        }
      })
      // 调用保存属性的函数
      this.saveAttr(row)
    },
    // 点击new Tag按钮显示输入框的处理函数
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //添加一个新标签事件处理函数
    AddTag(row) {
      if (this.inputValue.trim().length === 0) {
        this.inputVisible = false
        this.inputValue = ''
        return
      }
      if (!row.attr_vals) {
        row.attr_vals = []
      }
      row.attr_vals.push(this.inputValue)
      this.inputVisible = false
      this.inputValue = ''
      this.saveAttr(row)
    },
    // 保存修改过属性标签的函数
    async saveAttr(row) {
      const { data: res } = await this.$http.put(
        'categories/' + row.cat_id + '/attributes/' + row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$messgae.error('保存新参数失败~')
    },
    // 显示添加属性对话框
    openAdd(e) {
      if (this.selc_cateID.length === 0)
        return this.$message.error('请先选择商品分类哦~')
      this.addDialogInfo = e.target.innerText
      this.dialogVisible = true
    },
    // 关闭添加属性对话框
    closeAdd() {
      this.dialogVisible = false
      this.EditdialogVisible = false
      this.$refs.dialogForm.resetFields()
      this.YZattr_name = ''
      this.dialogForm.attr_name = ''
    },
    // 确认添加属性或参数
    AddTrue() {
      this.$refs.dialogForm.validate(async valid => {
        if (!valid) return
        if (this.activeName === 'first') {
          this.params.sel = 'many'
        }
        let cid = this.selc_cateID[this.selc_cateID.length - 1]
        const { data: res } = await this.$http.post(
          '/categories/' + cid + '/attributes',
          {
            attr_name: this.dialogForm.attr_name,
            attr_sel: this.params.sel
          }
        )
        if (res.meta.status !== 201)
          return this.$message.error('添加参数或属性失败~')
        this.$message.success('添加参数或属性成功~~')
        this.getAttrList()
        this.closeAdd()
      })
    },
    // 显示编辑对话框处理函数
    openEdit(data) {
      this.EditdialogVisible = true
      this.YZ.attr_name = data.attr_name
      this.YZ.id = data.attr_id
      this.YZ.sel = data.attr_sel
      if(typeof(data.attr_vals) !=='string' && data.attr_vals != ''){
        this.YZ.attr_vals = data.attr_vals.join(' ')
      }
      this.YZ.attr_vals = data.attr_vals
      this.dialogForm.attr_name = data.attr_name
    },
    // 编辑对话框内的确认按钮处理事件
    EditTrue() {
      if (this.YZ.attr_name == this.dialogForm.attr_name)
        return this.$message.error('啥也没改瞎点啥~')
      this.$refs.dialogForm.validate(async valid => {
        if (!valid) return
        let cid = this.selc_cateID[this.selc_cateID.length - 1]
        const { data: res } = await this.$http.put(
          '/categories/' + cid + '/attributes/' + this.YZ.id,
          {
            attr_name: this.dialogForm.attr_name,
            attr_sel: this.YZ.sel,
            attr_vals:this.YZ.attr_vals
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('更新参数或属性失败~')
        this.$message.success('更新参数或属性成功~~')
        this.getAttrList()
        this.closeAdd()
      })
    },
    // 删除按钮的处理事件
    async deleteAttr(data) {
      const res = await this.$confirm(
        '此操将删除该属性或参数, 是否继续?',
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {})
      if (res !== 'confirm') return this.$message.info('已取消删除~')
      let cid = this.selc_cateID[this.selc_cateID.length - 1]
      const { data: result } = await this.$http.delete(
        '/categories/' + cid + '/attributes/' + data.attr_id
      )
      if (result.meta.status !== 200)
        return this.$message.error('删除属性或参数失败~')
      this.$message.success('删除成功~~')
      this.getAttrList()
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.text_lh {
  line-height: 36px;
}
.el-tabs {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}
.input-new-tag {
  width: 100px;
}
</style>